<?php

class Admin_Model_GalleryItemMapper {
	protected $_dbTable;
	
	public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_GalleryItem');
        }
        return $this->_dbTable;
    }
    
    public function find($id,$sizeId)
    {
    	$t = $this->getDbTable();
    	$rowset = $t->find($id,$sizeId);
    	$row = $rowset->current();
    	return is_null($row)? null: new Admin_Model_GalleryItem($row->toArray());
    }
    
    public function findAllImageSizes($id){
    	$t1 = $this->getDbTable();
    	$t2 = new Admin_Model_DbTable_GallerySizes();
    	$tableName1 = $t1->info(Zend_Db_Table_Abstract::NAME);
    	$tableName2 = $t2->info(Zend_Db_Table_Abstract::NAME);
    	$set = $t1->fetchAll($t1->select()->setIntegrityCheck(false)
    			->from(array('t1'=>$tableName1),Zend_Db_Select::SQL_WILDCARD)
    			->join(array('t2'=>$tableName2), 't1.SizeId=t2.Id','Name as SizeName')
    			->where('t1.Id = ?',$id));
    	$result = array();
    	foreach($set as $r){
    		
    		$gi = new Admin_Model_GalleryItemAndSize($r->toArray());
    		$gi->CompositeId = $gi->getId().'-'.$gi->getSizeId();
    		
    		$result[] = $gi;
    	}
    	return $result;
    }
    
    public function save(Admin_Model_GalleryItem $item, $forceInsert = false, $onlyFields = false)
    {
    	$data = $item->toArray($onlyFields);
        if (null === ($id = $item->getId())) {
            unset($data['Id']);
            return $this->getDbTable()->insert($data);
        }
        elseif ($forceInsert){
        	return $this->getDbTable()->insert($data);
        }
        else {
            $this->getDbTable()->update($data, array('Id = ?' => $id, 'SizeId = ?'=>$item->getSizeId()));
            return 0;
        }
    }
    public function delete($id, $sizeId = null, $fromDB = true, $fromDisk = false){
    	$num = 0;
    	if ($fromDB){
    		$where = array("Id={$id}");
    		if (!is_null($sizeId)) $where[]="SizeId={$sizeId}";
    		$num = $this->getDbTable()->delete($where);
    	}
    	 
    	if ($fromDisk && (($fromDB && ($num>0)) || !$fromDB))
    	{
    		$d = dir(Admin_Model_GalleryItem::getPath());
    		$mask = $id.'_';
    		$mask .= $sizeId!=null?$sizeId.'_':''; 
    		
			while (false !== ($entry = $d->read())) {
				//echo '/*файл '.$entry.'*/';
				
				if (strpos($entry,$mask)===0){
					unlink(Admin_Model_GalleryItem::getPath().$entry);
					//echo '/* удалено'.Admin_Model_GalleryItem::getPath().$entry.' */';
				}
			}
			$d->close();
    	}
    }
    public function cloneImages($id){
    	$t  = $this->getDbTable();
    	$rowset = $t->fetchAll("Id=".$id);
    	$row = $rowset->current();
    	$id = null;
    	$result = array();
    	foreach($rowset as $row){
    		$data = $row->toArray();
    		$oldId = $data['Id'];
    		unset($data['Id']);
    		if ($id==null){
    			$id = $this->getDbTable()->insert($data);
    			$data['Id'] = $id['Id'];
    		}
    		else{
    			$data['Id'] = $id['Id'];
    			$this->getDbTable()->insert($data);
    		}
    		copy(Admin_Model_GalleryItem::getPath().$oldId.'_'.$data['SizeId'].'_'.$data['Width'].'x'.$data['Height'].'.'.$data['Ext'],
    			Admin_Model_GalleryItem::getPath().$data['Id'].'_'.$data['SizeId'].'_'.$data['Width'].'x'.$data['Height'].'.'.$data['Ext']
    			);
    		$result[] = new Admin_Model_GalleryItem($data);
    	}
    	return $result;
    }
}

?>